<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/5/13 16:52
 */

namespace App\Logic\Goods;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use Illuminate\Database\Eloquent\Builder;
use App\Models\Category;
use App\Models\Goods\Goods;
use Illuminate\Support\Arr;

class CategoryLogic extends CommLogic
{
    
    /**
     * @param $params
     * @return mixed
     */
    public function lists($params)
    {
        $query = Category::query()
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->get()->toArray();
        return $data;
    }

    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = Category::query()
            ->with('children')->where('parent_id', 0)
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }
        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])->toArray();

        foreach($data['data'] as &$item){
            $category = Category::query()->whereIn('id', array_column($item['children'], 'parent_id'))->get()->keyBy("id")->toArray();
            foreach($item['children'] as &$val){
                $val['thumb'] = Arr::first(array_column(json_decode($val['thumb'], true), 'url'));
                $val['parent_name'] = $val["parent_id"] > 0 ? $category[$val["parent_id"]]["name"] : '';
            }
            $item['thumb'] = Arr::first(array_column(json_decode($item['thumb'], true), 'url'));
        }

        return $data;
    }

    /**
     * @param $params
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function store($params)
    {
        $lockName = 'category_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        $data = array(
            'parent_id' => $params['parent_id'] ?? 0,
            'name' => $params['name'],
            'status' => $params['status'] ?? 1,
            'thumb' => json_encode($params['thumb'], true),
        );
        return Category::query()->create($data);
    }

    /**
     * @param $categoryId
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($data, $categoryId)
    {
        $data = Category::query()->where('id', $categoryId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        $categoryInfo = $data->toArray();
        $categoryInfo['thumb'] = json_decode($categoryInfo['thumb'], true);
        $goods = Goods::query()->whereIn('goods_id', explode(',', $categoryInfo["goods_ids"]))->get();
        foreach($goods as &$item){
            $item['goods_thumb'] = Arr::first(array_column(json_decode($item['goods_thumb'], true), 'url'));
        }
        $categoryInfo['goods'] = $goods;
        return $categoryInfo;
    }

    /**
     * @param $params
     * @param $categoryId
     * @return bool|int
     */
    public function update($params, $categoryId)
    {
        $lockName = 'category_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        $data = array(
            'parent_id' => $params['parent_id'] ?? 0,
            'name' => $params['name'],
            'status' => $params['status'] ?? 0,
            'thumb' => json_encode($params['thumb'], true),
        );
        return Category::query()->where('id', $categoryId)->update($data);
    }

    /**
     * @param $categoryId
     * @return bool|mixed|null
     */
    public function destroy($categoryId)
    {
        $data = Category::query()->where('id', $categoryId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        return Category::query()->where('id', $categoryId)->delete();
    }

    /**
     * 导入分类商品
     *
     * @param [type] $params
     * @return void
     */
    public function import($params)
    {
        $data = Category::query()->where('id', $params["category_id"])->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        return Category::query()->where('id', $params["category_id"])->update(["goods_ids" => $params["select_ids"]]);
    }
}
